import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:pin_input_text_field/pin_input_text_field.dart';

class VerificationCodePage extends StatefulWidget {
  final String phoneNumber;
  const VerificationCodePage({required this.phoneNumber});

  @override
  State<VerificationCodePage> createState() => _VerificationCodePageState();
}

class _VerificationCodePageState extends State<VerificationCodePage> {

  late String phoneNumber;

  var hasError = false;

  var verificationDone = false;

  var countDown = 60;

  var startCountDown = true;

  Timer? timer;

  @override
  void initState() {
    phoneNumber = widget.phoneNumber;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Stack(
          children: [
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 25.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  tips(),
                  SizedBox(
                    height: 75.h,
                  ),
                  verificationCode(),
                  verificationCodeCountDown(),
                ],
              ),
            ),
            const BackButton(color: Colors.black)
          ],
        ),
      ),
      backgroundColor: Colors.white,
    );
  }

  Widget tips() {
    String loginType = '输入验证码';
    String tip = '验证码会发送至  +86${phoneNumber}';
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          loginType,
          style: TextStyle(fontSize: 40.sp),
        ),
        Text(
          tip,
          style: TextStyle(
            fontSize: 20.sp,
            color: Colors.grey.shade400,
          ),
        ),
      ],
    );
  }

  Widget verificationCode() {
    Color pinColor = Colors.black;
    Widget statusWidget = Container();
    if (verificationDone) {
      if (hasError) {
        pinColor = Colors.red;
        statusWidget = error;
      } else {
        pinColor = Colors.green;
        statusWidget = success;
      }
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        PinInputTextField(
          onChanged: (str) {
            verification(str);
          },
          decoration: UnderlineDecoration(
              colorBuilder: PinListenColorBuilder(pinColor, Colors.black)),
        ),
        SizedBox(
          height: 10.h,
        ),
        statusWidget,
      ],
    );
  }

  Widget verificationCodeCountDown() {
    TextStyle textStyle =
    TextStyle(color: XColors.themeColor, fontSize: 16.sp);
    String text = '重新获取验证码';
    if (startCountDown) {
      textStyle = TextStyle(color: Colors.grey, fontSize: 16.sp);
      text = "${countDown}秒后重新获取";
    }
    return GestureDetector(
        onTap: () {
          if (!startCountDown) {
            resend();
          }
        },
        child: Text(
          text,
          style: textStyle,
        ));
  }

  Widget get error => Text.rich(
    TextSpan(children: [
      WidgetSpan(
          child: Icon(
            Icons.error,
            color: Colors.red,
            size: 24.w,
          ),
          alignment: PlaceholderAlignment.middle),
      const TextSpan(text: "请输入正确的验证码"),
    ]),
    style: TextStyle(color: Colors.red, fontSize: 20.sp),
  );

  Widget get success => Text.rich(
    TextSpan(children: [
      WidgetSpan(
          child: Container(
            margin: EdgeInsets.only(right: 10.w),
            width: 24.w,
            height: 24.w,
            decoration: const BoxDecoration(
              shape: BoxShape.circle,
              color: Colors.green,
            ),
            child: Icon(
              Icons.done,
              size: 20.w,
              color: Colors.white,
            ),
          ),
          alignment: PlaceholderAlignment.middle),
      const TextSpan(text: "验证完成"),
    ]),
    style: TextStyle(color: Colors.green, fontSize: 20.sp),
  );


  void verification(String code) {
    if (code.length == 6) {
      verificationDone = true;
      hasError = true;
    } else {
      verificationDone = false;
      hasError = false;
    }
  }

  void resend() {
    startCountDown = true;
    countDown = 60;
    startCountDownMethod();
  }

  void startCountDownMethod() {
    if (timer != null) {
      if (timer!.isActive) {
        timerClose();
      }
    }
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countDown <= 0) {
        timerClose();
        startCountDown = false;
      }
      countDown--;
    });
    setState(() {
    });
  }

  void timerClose() {
    timer?.cancel();
    timer = null;
  }

  @override
  void dispose() {
    super.dispose();
    timerClose();
  }
}
